<template>
  <a-modal v-model:visible="visible" :maskClosable="false" :title="title">
    <a-form
      ref="formRef"
      :model="form"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item
        label="登录账号"
        name="username"
        :rules="[
          { required: true, validator: validateUsername, trigger: 'change' },
        ]"
      >
        <a-input
          v-model:value="form.username"
          :maxlength="16"
          :readonly="type === 'edit'"
          placeholder="登录账号，最少5个字符，仅限英文或数字"
        />
      </a-form-item>
      <template v-if="type === 'add'">
        <a-form-item
          label="登录密码"
          name="password"
          :rules="[
            { required: true, validator: validatePass, trigger: 'change' },
          ]"
        >
          <a-input v-model:value="form.password" type="password" />
        </a-form-item>
        <a-form-item
          label="确认密码"
          name="rePwd"
          :rules="[
            { required: true, validator: validatePass2, trigger: 'change' },
          ]"
        >
          <a-input v-model:value="form.rePwd" type="password" />
        </a-form-item>
      </template>
      <a-form-item
        label="用户昵称"
        name="nickname"
        :rules="[{ required: true, message: '请填写用户昵称' }]"
      >
        <a-input v-model:value="form.nickname" :maxlength="16" />
      </a-form-item>
      <a-form-item
        label="手机号"
        name="mobile"
        :rules="[
          { required: true, validator: validateMobile, trigger: 'change' },
        ]"
      >
        <a-input v-model:value="form.mobile" :maxlength="11" />
      </a-form-item>
      <a-form-item
        label="邮箱"
        name="email"
      >
        <a-input type="email" v-model:value="form.email" />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-switch
          v-model:checked="form.status"
          checked-children="启动"
          un-checked-children="禁用"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="cancel" :loading="loading">取消</a-button>
      <a-button type="primary" :loading="loading" @click="submit(false)"
        >确定</a-button
      >
      <a-button
        type="primary"
        v-if="type === 'add'"
        :loading="loading"
        @click="submit(true)"
        >保存并继续</a-button
      >
    </template>
  </a-modal>
</template>
<script lang="ts">
import type { Rule } from "ant-design-vue/es/form";
import { defineComponent, reactive, ref, Ref, toRefs } from "vue";
import type { FormInstance } from "ant-design-vue";
import systemApis from "@/apis/system";
import { md5 } from "@/utils/tools";
export default defineComponent({
  name: "UserEditForm",
  setup(props, { emit }) {
    const formRef = ref<FormInstance>();
    const state = reactive({
      form: {
        username: "",
        password: "",
        rePwd: "",
        nickname: "",
        mobile: "",
        email: "",
        status: true,
        id: "",
      },
      visible: false as boolean,
      needUpdate: false as boolean,
      type: "add",
      title: "",
      loading: false as boolean,
    });

    const open = (type: "add" | "edit", data: any = {}) => {
      state.type = type;
      state.visible = true;
      state.needUpdate = false;
      state.title = type === "add" ? "新增账号" : "编辑账号";
      if (type === "add") {
        state.form = {
          username: "",
          password: "",
          rePwd: "",
          nickname: "",
          mobile: "",
          email: "",
          status: true,
          id: "",
        };
      } else {
        state.form = {
          username: data.username,
          password: data.password,
          rePwd: data.password,
          nickname: data.nickname,
          mobile: data.mobile,
          email: data.email,
          status: data.status,
          id: data.id,
        };
      }
      formRef.value?.resetFields();
      console.log(data);
    };

    const submit = async (_continue: boolean = false) => {
      try {
        const values = await formRef.value?.validateFields();
        console.log(values, state.form);
        if (state.type === "add") {
          let params = JSON.parse(JSON.stringify(state.form));
          delete params.rePwd;
          params.password = md5(params.password);
          const res: any = await systemApis.createUser(params);
          if (res.code === 0) {
            state.needUpdate = true;
            if (_continue) {
              state.form = {
                username: "",
                password: "",
                rePwd: "",
                nickname: "",
                mobile: "",
                email: "",
                status: true,
                id: "",
              };
              formRef.value?.resetFields();
            } else {
              cancel();
            }
          }
        }
        if (state.type === "edit") {
          const res: any = await systemApis.editUser(state.form);
          if (res.code === 0) {
            state.needUpdate = true;
            formRef.value?.resetFields();
            cancel();
          }
        }
      } catch (err) {}
    };

    const cancel = () => {
      if (state.needUpdate) {
        emit("submit");
      }
      state.visible = false;
    };

    // 表单校验
    const validateUsername = async (_rule: Rule, value: string) => {
      if (!value) {
        return Promise.reject("请输入登录账号");
      }
      if (!/^\w{5,}$/.test(value)) {
        return Promise.reject("格式错误，最少5个字符，仅限英文或数字");
      } else {
        return Promise.resolve();
      }
    };
    const validatePass = async (_rule: Rule, value: string) => {
      if (value === "") {
        return Promise.reject("请输入登录密码");
      } else {
        return Promise.resolve();
      }
    };
    const validatePass2 = async (_rule: Rule, value: string) => {
      if (value === "") {
        return Promise.reject("请重新输入登录密码");
      } else if (value !== state.form.password) {
        return Promise.reject("两次密码不一致");
      } else {
        return Promise.resolve();
      }
    };
    const validateMobile = async (_rule: Rule, value: string) => {
      if (!value) {
        return Promise.reject("请输入手机号码");
      }
      if (!/^1\d{10}$/.test(value)) {
        return Promise.reject("手机号码格式有误");
      } else {
        return Promise.resolve();
      }
    };
    return {
      formRef,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      validateUsername,
      validatePass,
      validatePass2,
      validateMobile,
      open,
      submit,
      cancel,
      ...toRefs(state),
    };
  },
});
</script>